require "Common/define"
require "Logic/Config"
require "Common/functions"
---@class HeroLinkManager
HeroLinkManager = {};
local this = HeroLinkManager;

local heroLinkCfg = nil;
local tableLink ={};  --智慧之链(dict)
this.mainHero = {};
--type,mainHeroId,slotInfos(list)
--slotId,partnerId,lastRemoveTime
function HeroLinkManager.init()
    this.heroLinkLevel = nil;
    this.HeroLinkLastLv = nil;
    heroLinkCfg = decodeJsonStrToTabel(dataTable.getGlobalString(424));
    tableLink = {};
    local index = 1;
    for i = 1, #heroLinkCfg do
        for j = 1, 6 do
            local subInfo = {};
            subInfo.slotId = index;
            subInfo.order = index;
            subInfo.unLock = heroLinkCfg[i];
            subInfo.lockType = 1
            subInfo.partnerId = nil;
            subInfo.lastRemoveTime = 0;
            table.insert(tableLink, subInfo);
            index = index + 1;
        end
    end
    this.maxTopLevel = 0
end

function HeroLinkManager.OnDestroy()
    this.heroLinkLevel = nil;
    this.HeroLinkLastLv = nil;
end

function HeroLinkManager.getAllLinkTableData()
    return heroLinkCfg or {};
end
function HeroLinkManager.setLinkInfos(table)
    for key, value in pairs(table) do
        for k, v in pairs(value.links) do
            local slotInfos = tableLink[v.slotId];
            if slotInfos~=nil then
                slotInfos.partnerId =tostring(v.partnerId);
                if slotInfos.partnerId == "0" then
                    slotInfos.partnerId = nil;
                end
                slotInfos.lastRemoveTime = v.lastRemoveTime;
            end
        end
    end
end

function HeroLinkManager.setLink(slotId,partnerId)
    local heroData = logicMgr.HeroManager.getHeroDatabyPartnerId(partnerId,true)
    local slotInfos = tableLink[slotId];
    if slotInfos~=nil then
        slotInfos.partnerId = tostring(partnerId);


        local _heroDic = {}
        _heroDic.hero_uniqueid = tostring(partnerId)
        _heroDic.hero_id = tostring(heroData.partnerModelId)
        --local _target_hero_id = tostring(tableLink[tonumber(heroData["type"])].mainHeroId)
        _heroDic.hero_level = tostring(heroData.level)--(HeroManager.getHeroShowLevelByPartnerId(tostring(_target_hero_id)))
        _heroDic.slot_id = tostring(slotId)
        TAManager.TrackByDictionary("hero_link_add",_heroDic)
    end
end

function HeroLinkManager.removeLink(partnerId,removeTime)
    local heroData = logicMgr.HeroManager.getHeroDatabyPartnerId(partnerId,true)
    for k, v in pairs(tableLink) do
        if v.partnerId == partnerId then
            v.partnerId = nil;
            v.lastRemoveTime = removeTime;


            --英雄解除链接后TA
            local _heroDic = {}
            _heroDic.hero_uniqueid = tostring(partnerId)
            _heroDic.hero_id = tostring(heroData.partnerModelId)
            _heroDic.hero_level = tostring(heroData.level)
            _heroDic.slot_id = tostring(v.order)
            TAManager.TrackByDictionary("hero_link_remove",_heroDic)
        end
    end
end

--type：1，后端同步  2，获取新英雄  3，点击继承
function HeroLinkManager.updateHeroForLinkMain(type, data)
    if type == 1 then
        this.mainHero = {}
        this.mainHero = data.linkHeros
    elseif type == 2 then
        if this.mainHero and #this.mainHero < 6 then
            this.mainHero[#this.mainHero+1] = data.newPartner
        end
    elseif type == 3 then
        for k,v in pairs(this.mainHero) do
            if tonumber(v) == tonumber(data.goOutLinkPartner) then
                this.mainHero[k] = data.goInLinkPartner
            end
        end
    end
    local minLevel = 1
    if this.mainHero then
        minLevel = logicMgr.HeroManager.GetHeroLevel(this.mainHero[1])
        for k,v in pairs(this.mainHero) do
            local heroLevel = logicMgr.HeroManager.GetHeroLevel(v)
            if heroLevel < minLevel then
                minLevel = heroLevel
            end
        end
        this.heroLinkLevel = minLevel
    end
    --logicMgr.HeroManager.UpdateAllBaseAttr()
    --partnerHandler.ReqHeroPower(0, false)
    --local lists = logicMgr.HeroManager.getOwnerHeroListReadOnly();
    --local list = lists;
    --table.sort(list, function (a,b)
    --    if a.level ~= b.level then return a.level > b.level; end
    --    if a.star ~= b.star then return a.star > b.star; end
    --    if a.type ~= b.type then return a.type > b.type; end
    --    --if logicMgr.HeroManager.HeroTypeList[a.type] ~= logicMgr.HeroManager.HeroTypeList[b.type] then return logicMgr.HeroManager.HeroTypeList[a.type] > logicMgr.HeroManager.HeroTypeList[b.type]; end
    --    return tonumber(a["partnerModelId"]) < tonumber(b["partnerModelId"]);
    --end);
    --local num = 6;
    --if #list < 6 then
    --    num = #list;
    --    this.heroLinkLevel = 1;
    --else
    --    this.heroLinkLevel = list[6].level;
    --end
    --this.mainHero = {};
    --for i=1, num do
    --    table.insert(this.mainHero, list[i].partnerId);
    --end
end

function HeroLinkManager.getMainList()
    return this.mainHero or {};
end

function HeroLinkManager.clearSlotCd(orderId, partnerType)
    local data = tableLink[orderId];
    if data ~= nil then
        data.lastRemoveTime = 0;
    end
end

---(废弃)
function HeroLinkManager.getLinkInfosByType(type)
    --local data = tableLink[type];
    --if data~=nil then
    --    return clone(data);
    --end
    return nil;
end

function HeroLinkManager.getLinkInfoBySlotId(slotId)
    --for key, value in pairs(tableLink) do
    --    for i = 1,#value.slotInfos  do
    --        if value.slotInfos[i].slotId == slotId then
    --        end
    --    end
    --end
    if tableLink[slotId] then
        return clone(tableLink[slotId]);
    end
    return nil;
end

function HeroLinkManager.isInLink(partnerId,isContainMain)
    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroLink) then
        return false;
    end
    if this.isMainHero(partnerId) then
        return isContainMain;
    end
    --if isContainMain and this.isMainHero(partnerId) then
    --    return true;
    --end
    --for key, value in pairs(tableLink) do
    --    if value.partnerId and value.partnerId == partnerId then
    --        return true;
    --    end
    --end
    local data = logicMgr.HeroManager.getHeroDatabyPartnerId(partnerId, true)
    if data and data.level > 1 then
        return false;
    end
    return true;
end
---根据品质是否解锁(废弃)
function HeroLinkManager.IsNotLockByQuality(type,qualityNum)
    local list = logicMgr.HeroManager.getOwnerHeroListNoClone(type)
    local count = 0
    for _,v in ipairs(list) do
        if v.star >= qualityNum then
            count = count + 1
        end
    end
    return count
end

function HeroLinkManager.isMainHero(partnerId)
    for key, value in pairs(this.mainHero) do
        if value == partnerId then
            return true;
        end
    end
    return false;
end
--- 获取所有职业智慧链的最低等级(废弃)
function HeroLinkManager.GetMiniLevel()
    local miniLev = 999999
    --for _, v in pairs(tableLink) do
    --    local lev = HeroLinkManager.GetMiniLevlBySchool(v["type"])
    --    miniLev = miniLev > lev and lev or miniLev
    --end
    return miniLev
end

--- 获取所有职业智慧链的等级
function HeroLinkManager.GetHeroLevel()

    --local level = 0
    --for _, v in pairs(tableLink) do
    --    local lev = HeroLinkManager.GetMiniLevlBySchool(v["type"])
    --    level = level + lev;
    --end
    --level = math.floor(level / 6)
    ---- 智慧之链等级变化
    --local old = this.HeroLinkLastLv
    --this.HeroLinkLastLv = level
    --if old ~= this.HeroLinkLastLv then
    --    local _linkDic = {}
    --    _linkDic.last_lv = old
    --    _linkDic.new_lv = this.HeroLinkLastLv
    --    TAManager.TrackByDictionary("hero_link_lv_change",_linkDic)
    --end
    --return this.HeroLinkLastLv
    return this.heroLinkLevel or 1;
end
function HeroLinkManager.getAllLinkTableData()
    return heroLinkCfg or {};
end
--- 获取所有职业智慧链的等级
function HeroLinkManager.GetHeroLevelByType()
    local ll = this.heroLinkLevel or 1;
    local phase=0
    if this.IsTopLevelOpen() then
        ll,phase = this.GetTopLevel()
    end
    local old = this.HeroLinkLastLv
    this.HeroLinkLastLv = ll
    if old and old ~= this.HeroLinkLastLv then
        local _linkDic = {}
        _linkDic.last_lv = old
        _linkDic.new_lv = this.HeroLinkLastLv
        TAManager.TrackByDictionary("hero_link_lv_change",_linkDic)
        TAManager.UserSet("hero_link_lv", this.HeroLinkLastLv);
    end
    return ll,phase;
end

--- 获取对应职业智慧链的最低等级(废弃)
function HeroLinkManager.GetMiniLevlBySchool(type)
    --local data = tableLink[type];
    local miniLev = 0
    --if data then
        --local rootHeroInfo = logicMgr.HeroManager.getHeroDatabyPartnerId(data["mainHeroId"],true)
        --if rootHeroInfo then
        --    --miniLev = miniLev > rootHeroInfo["level"] and rootHeroInfo["level"] or miniLev
        --    miniLev = rootHeroInfo["level"];
        --end
        --for _, v in pairs(data["slotInfos"]) do
        --    if v["partnerId"] and v["partnerId"] ~= "" then
        --        local heroInfo = logicMgr.HeroManager.getHeroDatabyPartnerId(v["partnerId"])
        --        if heroInfo then
        --            miniLev = miniLev > heroInfo["level"] and heroInfo["level"] or miniLev
        --        end
        --    end
        --end
    --end
    return miniLev
end
--巅峰等级开启了
function HeroLinkManager.IsTopLevelOpen()
    if not this.isTopOpen then
        this.isTopOpen = logicMgr.HeroManager.IsAllTypeHeroReachLimitLevel()
    end
    return this.isTopOpen
end
--巅峰等级
function HeroLinkManager.GetTopLevel()
    if not this.topLevel or this.topLevel == 0 then
        this.topLevel = dataTable.getGlobalInt(250)
        this.topPhase=1
    end
    return this.topLevel,this.topPhase
end
function HeroLinkManager.GetMaxTopLevel()
    if this.maxTopLevel > 0 then
        return this.maxTopLevel
    end
    local cfg = dataTable.getDataTable("t_characterexp")
    this.maxTopLevel = table.getn(cfg)
    return this.maxTopLevel
end
--巅峰等级红点提示
function HeroLinkManager.TopLevelRedDot()
    --首次
    local flag = this.IsTopLevelFirstReachNeedTip()
    if flag then return true end
    --巅峰解锁
    if not logicMgr.HeroManager.IsAllTypeHeroReachLimitLevel() then
        return false
    end
    --可升级
    local topLevel,topPhase = this.GetTopLevel()
    if topLevel >= logicMgr.HeroLinkManager.getTopLevelLimit() then
        return false;
    end
    local cfg = dataTable.getDataTableByStringId("t_characterexp",MakeTopLevelId(topLevel,topPhase))
    local costList = decodeJsonStrToTabel(cfg.f_HeroCost)
    for k,v in pairs(costList) do
        local own = ItemManager.getBagNumByTableID(v[1])
        local need = v[2]
        if own < need then
            return false
        end
    end
   local exp = ItemManager.getBagNumByTableID(CurrencyEnum.HeroExp)
    if exp < cfg.f_HeroExp then
        return false
    end
    return true
end
--首次到达巅峰等级是否提示过
function HeroLinkManager.IsTopLevelFirstReachNeedTip()
    local tip = GetPlayerPrefs("TopLevelTipOver")
    if tip ~= "1" then
        return  logicMgr.HeroManager.IsAllTypeHeroReachLimitLevel()
    end
    return false
end
function HeroLinkManager.SetTopLevelTipOver()
    SetPlayerPrefs("TopLevelTipOver","1")
    RedDotsHeroLinkHandler.update()
end
function HeroLinkManager.getTopLevelLimit()
    local cfg =  dataTable.getDataTableByStringId("t_global",388)
    local cfg2 = dataTable.getDataTableByStringId("t_global",389).f_string_value
    return cfg.f_int_value + logicMgr.HeroManager.GetHerosByStar(tonumber(cfg2[1])) *tonumber(cfg2[2])
end
return HeroLinkManager